package com.gframework.fenci.tree;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * 混淆字关联信息存储类
 * @author Ghwolf
 */
class ErrorProneWord implements Iterable<Character>,Serializable{
	private static final long serialVersionUID = -7719531083610691674L;
	
	private final List<Character[]> list = new ArrayList<>(4);
	private final Character value ;
	
	ErrorProneWord(Character value){
		this.value = value ;
	}
	
	public static Iterable<Character> createSimpleIterable(char c){
		return new SipmleCharacterIterator(c);
	}
	
	public void add(Character[] word){
		if (word == null || word.length == 0) return ;
		this.list.add(word);
	}
	
	/**
	 * 迭代器值会返回当前char值一次而且是第一次
	 */
	@Override
	public Iterator<Character> iterator() {
		return new ErrorProneWordIterator();
	}
	
	class ErrorProneWordIterator implements Iterator<Character> {
		
		private int index = 0 ;
		private int foot = 0 ;
		private Character nextValue = ErrorProneWord.this.value;
		ErrorProneWordIterator() {
		}

		@Override
		public boolean hasNext() {
			if (this.nextValue == null) {
				if (index >= ErrorProneWord.this.list.size()) {
					return false ;
				}
				Character[] arr = ErrorProneWord.this.list.get(index);
				Character c = arr[foot ++];
				if (foot >= arr.length) {
					foot = 0;
					index ++;
				}
				if (c.equals(ErrorProneWord.this.value)) {
					return hasNext();
				} else {
					this.nextValue = c;
				}
			}
			return true;
		}

		@Override
		public Character next() {
			if (!this.hasNext()) {
				throw new NoSuchElementException();
			}
			Character c = this.nextValue;
			this.nextValue = null;
			return c;
		}
		
	}
	
	static class SipmleCharacterIterator implements Iterator<Character>,Iterable<Character> {
		
		private Character value ;
		SipmleCharacterIterator(Character value) {
			this.value = value ;
		}
		
		@Override
		public boolean hasNext() {
			return this.value != null ;
		}
		
		@Override
		public Character next() {
			if (this.value == null) {
				throw new NoSuchElementException();
			}
			Character c = this.value;
			this.value = null ;
			return c;
		}

		@Override
		public Iterator<Character> iterator() {
			return this;
		}
		
	}
	
}
